<?php
namespace Sdk\Vip\Translator;

use Marmot\Core;
use Marmot\Interfaces\IRestfulTranslator;
use Sdk\Common\Translator\RestfulTranslatorTrait;

use Sdk\Vip\Model\Vip;
use Sdk\Vip\Model\NullVip;

class VipRestfulTranslator implements IRestfulTranslator
{
    use RestfulTranslatorTrait;
    
    public function arrayToObject(array $expression, $vip = null)
    {
        if (empty($expression)) {
            return NullVip::getInstance();
        }

        if ($vip == null) {
            $vip = new Vip();
        }
       
        $data = $expression['data'];
        $attributes = isset($data['attributes']) ? $data['attributes'] : array();

        if (isset($data['id'])) {
            $vip->setId($data['id']);
        }
        if (isset($attributes['indicators'])) {
            $vip->setIndicators($attributes['indicators']);
        }
        if (isset($attributes['updateTime'])) {
            $vip->setUpdateTime($attributes['updateTime']);
        }

        return $vip;
    }

    public function objectToArray($vip, array $keys = array())
    {
        if (!$vip instanceof Vip) {
            return array();
        }

        if (empty($keys)) {
            $keys = array(
                'id',
                'indicators',
                'staff'
            );
        }

        $expression = array(
            'data' => array(
                'type' => 'vip'
            )
        );

        if (in_array('id', $keys)) {
            $expression['data']['id'] = $vip->getId();
        }

        $attributes = array();

        if (in_array('indicators', $keys)) {
            foreach ($vip->getIndicators() as $value) {
                $indicators[] = array(
                    'name' => $value['name'],
                    'consumerMinPrice' => intval($value['consumerMinPrice']),
                    'consumerMaxPrice' => intval($value['consumerMaxPrice'])
                );
            }
            $attributes['indicators'] = $indicators;
        }
        $expression['data']['attributes'] = $attributes;

        if (in_array('staff', $keys)) {
            $staffRelationships = array(
                'type' => 'staff',
                'id' => strval(Core::$container->get('staff')->getId())
            );

            $expression['data']['relationships']['staff']['data'] = $staffRelationships;
        }
        
        return $expression;
    }
}
